import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart' hide LocationAccuracy;
import 'package:http/http.dart' as http;

class GoogleMapUtils {
  static late GoogleMapController _mapController;
  static final Set<Marker> _markers = {};
  static Location location = Location();

  // 初始化地图配置
  static Future<void> initMap(GoogleMapController controller) async {
    _mapController = controller;
    await _checkLocationPermission();
    // await _enableMyLocationLayer();
  }

  // 添加标记点
  static Marker addMarker({
    required LatLng position,
    String? markerId,
    String? infoText,
    BitmapDescriptor? icon,
  }) {
    final marker = Marker(
      markerId: MarkerId(markerId ?? 'default_${DateTime.now().millisecondsSinceEpoch}'),
      position: position,
      infoWindow: infoText != null ? InfoWindow(title: infoText) : InfoWindow.noText,
      icon: icon ?? BitmapDescriptor.defaultMarker,
    );
    _markers.add(marker);
    return marker;
  }

  // 清除所有标记
  static void clearMarkers() {
    _markers.clear();
  }

  // 移动相机到指定位置
  static Future<void> animateToPosition(LatLng target, {double zoom = 14}) async {
    await _mapController.animateCamera(
      CameraUpdate.newLatLngZoom(target, zoom),
    );
  }

  // 获取当前设备位置
  static Future<LatLng?> getCurrentLocation() async {
    final locData = await location.getLocation();
    return LatLng(locData.latitude!, locData.longitude!);
  }

  // 权限检查与请求
  static Future<bool> _checkLocationPermission() async {
    bool serviceEnabled = await location.serviceEnabled();
    await location.requestService();
    if (!serviceEnabled) {
      serviceEnabled = await location.requestService();
      if (!serviceEnabled) return false;
    }

    var permission = await location.hasPermission();
    if (permission == PermissionStatus.denied) {
      permission = await location.requestPermission();
      if (permission != PermissionStatus.granted) return false;
    }
    return true;
  }

  //
  // // 启用设备定位图层
  // static Future<void> _enableMyLocationLayer() async {
  //   await location.enableBackgroundMode(enable: true);
  //   location.changeSettings(
  //     accuracy: LocationAccuracy.high,
  //     interval: 5000,
  //   );
  // }

  // 销毁资源
  static void dispose() {
    _mapController.dispose();
    _markers.clear();
  }

  static Future<List<Place>> fetchNearbyPlaces() async {
    await _checkLocationPermission();
    // 获取当前位置
    final position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    var lat = position.latitude;
    var lng = position.longitude;

    print("fetchNearbyPlaces position ${position.toString()}");

    const apiKey = 'AIzaSyARFX_7KM8sMxCeXLh6q2BZWnrd1kHfXss';
    final url = Uri.parse('https://maps.googleapis.com/maps/api/place/nearbysearch/json'
        '?location=$lat,$lng&radius=1000&type=restaurant&key=$apiKey&rankby=distance');

    final response = await http.get(url);
    print("fetchNearbyPlaces response.body ${response.body}");
    if (response.statusCode == 200) {
      return _parsePlaces(response.body);
    } else {
      debugPrint("fetchNearbyPlaces error: ${response}");
      return [];
      // throw Exception('获取数据失败');
    }
  }

  static Future<Position?> getCurrentPosition() async {
    try {
      EasyLoading.show(maskType: EasyLoadingMaskType.clear);
      await _checkLocationPermission();
      final position = await Geolocator.getCurrentPosition(
          locationSettings: const LocationSettings(accuracy: LocationAccuracy.bestForNavigation));
      return position;
    } catch (e) {
      EasyLoading.dismiss();
      print("获取位置失败：$e");
    }
    return null;
  }

  static List<Place> _parsePlaces(String responseBody) {
    final data = json.decode(responseBody);
    return (data['results'] as List).map((item) {
      return Place(
          name: item['name'],
          address: item['vicinity'],
          lat: item['geometry']['location']['lat'],
          lng: item['geometry']['location']['lng']);
    }).toList();
  }
}

class Place {
  final String name;
  final String address;
  final double lat;
  final double lng;

  Place({required this.name, required this.address, required this.lat, required this.lng});

  factory Place.fromJson(Map<String, dynamic> json) {
    final location = json['geometry']['location'];
    return Place(
      name: json['name'],
      address: json['vicinity'] ?? 'No address',
      lat: location['lat'],
      lng: location['lng'],
    );
  }
}
